package info.wangyuan.agent.service.curd.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import info.wangyuan.agent.entity.po.QrCode;
import info.wangyuan.agent.exception.BusinessException;
import info.wangyuan.agent.mapper.QrCodeMapper;
import info.wangyuan.agent.service.curd.QrCodeService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

/**
 * 二维码服务实现类
 *
 * @author Albert
 * @since 2025-08-04 13:09:18
 */
@Service
public class QrCodeServiceImpl extends ServiceImpl<QrCodeMapper, QrCode> implements QrCodeService {

    private final QrCodeMapper qrCodeMapper;

    public QrCodeServiceImpl(QrCodeMapper qrCodeMapper) {
        this.qrCodeMapper = qrCodeMapper;
    }

    @Override
    public void saveQrCode(MultipartFile file, String name) {
        try {
            qrCodeMapper.insert(QrCode.builder()
                    .name(name)
                    .base64(Base64.getEncoder().encodeToString(file.getBytes()))
                    .build()
            );
        } catch (IOException e) {
            throw new BusinessException("上传失败", e);
        }
    }

    @Override
    public String getQrCodeBase64(Integer id) {
        QrCode qrCode = qrCodeMapper.selectById(id);
        if (qrCode == null) {
            throw new BusinessException("未找到该二维码");
        }
        return "data:image/png;base64," + qrCode.getBase64();
    }

    @Override
    public void updateQrCode(MultipartFile file, Integer id) {
        try {
            qrCodeMapper.updateById(QrCode.builder()
                    .id(id)
                    .base64(Base64.getEncoder().encodeToString(file.getBytes()))
                    .build()
            );
        } catch (IOException e) {
            throw new BusinessException("上传失败", e);
        }
    }

    @Override
    public void deleteQrCode(Integer id) {
        int delete = qrCodeMapper.deleteById(id);
        if (delete == 0) {
            throw new BusinessException("删除失败，未找到该二维码");
        }
    }
}
